package com.baizhi.hospital.aspect;

import com.baizhi.hospital.annotation.LogAnnotation;
import com.baizhi.hospital.dao.LogDao;
import com.baizhi.hospital.entity.Log;
import com.baizhi.hospital.entity.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration
@Aspect
public class LogAspect {
    private Logger logger=LoggerFactory.getLogger(LogAspect.class);
    @Autowired(required = false)
    private LogDao logDao;
    /**
     * 1.写增强
     * 2.定义切入点@annotation(com.baizhi.annotation.LogAnnotation)切入点表达式
     *
     * */
    @After("@annotation(com.baizhi.hospital.annotation.LogAnnotation)")
    public void logAfter(JoinPoint joinPoint){
        Log log=new Log();
        //1.日志信息的采集
        //日志时间
        log.setLogDate(new Date());

        //operator 日志操作人的真实姓名 从session作用域中获取操作者的真实姓名
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User user=(User) session.getAttribute("user");
        log.setOperator(user.getRealName());

        // content 操作内容
        //joinpoint.getargs():获取带参方法的参数
        //joinpoint.getTarget():.获取他们的目标对象信息
        //joinpoint.getSignature():(signature是信号,标识的意思):获取被增强的方法相关信息
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        String value = annotation.value();
        log.setContent(value);
        //获取type 1登录 2诊断
        String type = annotation.type();
        //log.setType(2);
        log.setType(Integer.parseInt(type));
        logger.debug(log.toString());
        //日志队形添加数据库
        logDao.insertLog(log);
    }

}
